import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from '../../api'

const state = {
  cartList: [],
}
const mutations = {
  GETCARTLIST(state, cartList) {
    state.cartList = cartList
  },
}

const actions = {
  async getCartList({ commit }) {
    let result = await reqCartList()
    if (result.code == 200) {
      commit('GETCARTLIST', result.data)
    }
  },

  // 删除购物车某个产品
  async deleteCartListById({ commit }, skuId) {
    let result = await reqDeleteCartById(skuId)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('fail'))
    }
  },

  // 修改购物车某个产品的选中状态
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedById(skuId, isChecked)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('fail'))
    }
  },

  // 删除全部勾选的商品
  deleteAllCheckedCart({ dispatch, getters }) {
    // context: 就相当于shopcart组件的小仓库，里面有 dispatch, getters, state等
    // 获取购物车中的全部商品
    let PromisAll = []
    getters.cartList.cartInfoList.forEach((item) => {
      // 只删除选中的商品
      let promise = item.isChecked == 1 ? dispatch('deleteCartListById', item.skuId) : ''
      PromisAll.push(promise)
    })
    // 只要全部的promise都成功，返回的结果为成功，否则失败。
    return Promise.all(PromisAll)
  },

  // 修改全部产品的勾选状态
  updateAllCartChecked({ dispatch, state }, isChecked) {
    let promisAll = []
    state.cartList[0].cartInfoList.forEach((item) => {
      let promise = dispatch('updateCheckedById', {
        skuId: item.skuId,
        isChecked,
      })
      promisAll.push(promise)
    })
    return Promise.all(promisAll)
  },
}

const getters = {
  cartList(state) {
    return state.cartList[0] || {}
  },
}

export default {
  state,
  mutations,
  actions,
  getters,
}
